var People = Backbone.Model.extend({
   subalbum: function() { return 'c' + gallery._currentPid; }
});

var PeopleCollection = Backbone.Collection.extend({
    model: People,
    comparator: function(item) {
        return item.get('pid');
    }
});

function removeFallbacks(){
  var query = $('.jstest,.gallery');
        if(query.length){
          query.remove();
        }
}

var PeopleInfoView = Backbone.View.extend({
    head_info: $('#people_head_info'),
    head_info_tmpl: $('#people_head_info_tmpl'),
    people_four_vistors: $('#people_four_vistors'),
    people_four_vistors_tmpl: $('#people_four_vistors_tmpl'),
    user_ratings_infos_tmpl: $('#user_ratings_tmpl'),
    user_ratings_infos: $('#user_ratings'),
    people_infos_tmpl: $('#people_infos_tmpl'),
    people_infos: $('#people_infos'),
    renderById: function(id) {
        var sg = this;
        $(this.head_info).fadeOut('fast', function() {
            console.log('!!!' + id + typeof(sg.model));
            var res = sg.model.getByCid({cid: id});
            console.log(res);
            
                
                var date = new Date(parseInt(res.attributes.reg_time.substr(0, 4)), parseInt(res.attributes.reg_time.substr(4, 2)), parseInt(res.attributes.reg_time.substr(6, 2)));
                console.log(date.toJSON());
                var currentTime = new Date();
                var diff = (currentTime - date) / 31536000000;
                res.attributes['year'] = Math.ceil(diff);
                res.attributes['rank'] = res.attributes.point;
            
            $(sg.head_info).empty();
            $.tmpl(sg.head_info_tmpl, [res]).appendTo(sg.head_info);
            $(sg.head_info).fadeIn('fast');
        });
        
        $(this.people_four_vistors).fadeOut('fast', function() {

            $(sg.people_four_vistors).empty();
            var four_vistors = sg.model.shuffle().slice(0,4);
            console.log(four_vistors);
            $(sg.people_four_vistors).empty();
            $.tmpl(sg.people_four_vistors_tmpl, four_vistors).appendTo(sg.people_four_vistors);
            console.log($.tmpl(sg.people_four_vistors_tmpl, four_vistors));

            $(sg.people_four_vistors).fadeIn('fast');
        });
        
        $(this.user_ratings_infos).fadeOut('fast', function() {
            $(sg.user_ratings_infos).empty();
            var users = sg.model.shuffle();
            res = [];
            for (i in users)
            {
                res.push({name:users[i].attributes.name, r1:Math.floor(Math.random()*11), r2:Math.floor(Math.random()*11), 
                    r3:Math.floor(Math.random()*11), r4:Math.floor(Math.random()*11)});
            }
            
            $.tmpl(sg.user_ratings_infos_tmpl, res).appendTo(sg.user_ratings_infos);
            $(sg.user_ratings_infos).fadeIn('fast');
        });
        
        $(this.people_infos).fadeOut('fast', function() {
            $(sg.people_infos).empty();
            var users = sg.model.shuffle();
            res = [];
            for (i in users)
            {
                res.push({name:users[i].attributes.name, year:Math.floor(Math.random()*5)+1, rank:parseInt(i)+1});
            }
            $.tmpl(sg.people_infos_tmpl, res).appendTo(sg.people_infos);
            $(sg.people_infos).fadeIn('fast');
        });
        return this;
    },
    show: function(bShow) {
        if (bShow) {
            $('#people_info_div').show();
        } else {
            $('#people_info_div').hide();
        }
    }
});

var IndexView = Backbone.View.extend({
    el: $('#star_people'),
    indexTemplate: $("#people_template1").template(),
    el2: $('#all_people'),
    indexTemplate2: $("#people_template2").template(),
    people_pagination: $('#people_pagination'),

    render: function() {
        removeFallbacks();
        var sg = this;
        console.log("l26: " + typeof(this.el) + this.el);
        $(this.el).fadeOut('fast', function() {
        $(sg.el).empty();
        $.tmpl(sg.indexTemplate, sg.model.shuffle().slice(0,4)).appendTo(sg.el);
        console.log(sg.model.toArray());
        $(sg.el).fadeIn('fast');
        });
        return this;
    },
    
    render2: function(id) {
    	if (id == null)
    		id = 0;
    		
        // 先绘制导游格子
        var sg = this;
        var n = 0;
        console.log("l26: " + typeof (this.el) + this.el);
        $(this.el2).fadeOut('fast', function() {
            $(sg.el2).empty();

            n = sg.model.toArray().length;
            var arr = sg.model.toArray().slice(id * 8, Math.min(id * 8 + 8, n));
            console.log(arr.length);
            for(var i in arr) {
                console.log(i);
                var arg = [arr[i].attributes.reg_time.substr(0, 4), parseInt(arr[i].attributes.reg_time.substr(4, 2)), parseInt(arr[i].attributes.reg_time.substr(6, 2))];
                console.log(arg);
                var date = new Date(parseInt(arr[i].attributes.reg_time.substr(0, 4)), parseInt(arr[i].attributes.reg_time.substr(4, 2)), parseInt(arr[i].attributes.reg_time.substr(6, 2)));
                console.log(date.toJSON());
                var currentTime = new Date();
                var diff = (currentTime - date) / 31536000000;
                arr[i].attributes['year'] = Math.ceil(diff);
                arr[i].attributes['rank'] = arr[i].attributes.point;
                console.log('test');
            }
            $.tmpl(sg.indexTemplate2, arr).appendTo(sg.el2);
            console.log(sg.model.toArray());
            $(sg.el2).fadeIn('fast');
        });
        
        // 接着绘制页面按钮
        $(this.people_pagination).fadeOut('fast', function() {
            $(sg.people_pagination).empty();
            var ul = $(sg.people_pagination).append('<ul></ul>').find('ul');
            var pages = [];
            for (var i = 0; i < n/8; i++)
            {
                var pageInfo = {'page':i+1, 'path':'index/'+i};
                pages.push(pageInfo);
            }
            $.tmpl('<li><a href="#${path}">${page}</a></li>',pages).appendTo(ul);
            ul.find('li:eq('+id+')').addClass('active');
            $(sg.people_pagination).fadeIn('fast');
        });
        return this;
    },
    
    show: function(bShow) {
        if (bShow) {
            $('#people_index_div').show();
        } else {
            $('#people_index_div').hide();
        }
    }
});

var SubalbumView = Backbone.View.extend({
    el: $('#main'),
    indexTemplate: $("#subindexTmpl").template(),
    
    initialize: function(options){

    },

    render: function() {
        var sg = this;
        removeFallbacks();
        this.el.fadeOut('fast', function() {
            sg.el.empty();
            $.tmpl(sg.indexTemplate, sg.model.toArray()).appendTo(sg.el);
            sg.el.fadeIn('fast');
        });
        return this;
    }

});

var PeoplePage = Backbone.Router.extend({
    _index: null,
    _peoples: null,
    _album :null,
	_subalbums:null,
	_subphotos:null,
	_data:null,
	_photosview:null,
	_currentsub:null,

    routes: {
        "": "index",
        "index/:id": "index",
        "people": "index",
        "people/:id": "people_info",
        "people/:id/" : "directphoto",
        "people/:id/:num" : "hashphoto"
    },

    initialize: function(options) {
    
        var ws = this;
       
        if (this._index === null){
            $.ajax({
                url: 'data/people.json',
                dataType: 'json',
                data: {},
                success: function(data) {
				    ws._data = data;
                    ws._peoples = new PeopleCollection(data);
                    ws._index = new IndexView({model: ws._peoples});
                    ws._people_info = new PeopleInfoView({model: ws._peoples});
                    Backbone.history.loadUrl();
                }
            });
            return this;
        }
        return this;
    },


    /**
	 * Handle rendering the initial view for the application
	 * @type function
	*/
    index: function(id) {
    	if (this._index === null)
    		{
    			console.log('???');
    			return;
    		}
    	this._people_info.show(false);
        this._index.show(true);
        this._index.render();
        this._index.render2(id);
    },
	

	/**
	 * Gallery -> hashsub: Handle URL routing for subalbums. As subalbums aren't traversed 
	 * in the default initialization of the app, here we create a new PhotoCollection for a 
	 * particular subalbum based on indices passed through the UI. We then create a new SubalbumView 
	 * instance, render the subalbums and set the current subphotos array to contain our subalbum Photo 
	 * items. All of this is cached using the CacheProvider we defined earlier
	 * @type function
	 * @param {String} id An ID specific to a particular subalbum based on CIDs
	 */
	people_info:function(id){
       if (this._index === null)
       {
            console.log('???');
            return;
       }
       console.log('???!!!');
	   this._index.show(false);
       this._people_info.show(true);
       this._people_info.renderById(id);
	},
	
	directphoto: function(id){

	},

	/**
	 * Gallery -> hashphoto: Handle routing for access to specific images within subalbums. This method 
	 * checks to see if an existing subphotos object exists (ie. if we've already visited the 
	 * subalbum before). If it doesn't, we generate a new PhotoCollection and finally create 
	 * a new PhotoView to display the image that was being queried for. As per hashsub, variable/data 
	 * caching is employed here too
	 * @type function
	 * @param {String} num An ID specific to a particular image being accessed
	 * @param {Integer} id An ID specific to a particular subalbum being accessed
	 */
	  hashphoto: function(num, id){
	    this._currentsub = num;
	    
	    num = num.replace('c','');
	    
		if(this._subphotos == undefined){
		   this._subphotos = cache.get('pc' + num) || cache.set('pc' + num, new PhotoCollection(this._data[num].subalbum));
		 }	
	    this._subphotos.at(id)._view = new PhotoView({model: this._subphotos.at(id)});
	    this._subphotos.at(id)._view.render();
	    
	  }
});


people_page = new PeoplePage();
Backbone.history.start();